import Taro from "@tarojs/taro";
import dayjs from 'dayjs'
import toObject from 'dayjs/plugin/toObject'
import { getStorage } from '../pages/components/utils'

const storage = getStorage()
const divideUrl = (url) => {
    let urlSearch = "";
    let urlHash = "";
    let urlPath = "";
    let hashIndex = url.indexOf("#/"); //hash 的位置,查询是否有哈希，有先分离，后面加回来
    let searchIndex = url.indexOf("?"); //参数的位置
    if (hashIndex !== -1) {
        //不存在hash
        if (hashIndex < searchIndex) {
            //哈希在前面，直接切
            urlSearch = url.split("#/")[1].split("?")[1];
            urlPath = url.split("#/")[0];
            urlHash = url.split("#/")[1].split("?")[0];
        } else {
            //在后面，需要先去掉哈希
            urlSearch = url.split("#/")[0].split("?")[1];
            urlPath = url.split("#/")[0].split("?")[0];
            urlHash = url.split("#/")[1];
        }
    } else {
        urlSearch = url.split("?")[1];
        urlPath = url.split("?")[0];
    }
    return {
        urlHash,
        urlPath,
        urlSearch,
    };
};

//获取url参数
function getUrlQueryVariable(url, variable) {
    if (typeof url === "string" && !url.includes("?")) {
        //判断是否为字符串和包含？，不是则返回false
        return false;
    }
    let { urlSearch } = divideUrl(url);
    var vars = urlSearch.split("&");
    for (var i = 0; i < vars.length; i++) {
        var pair = vars[i].split("=");
        if (pair[0] === variable) {
            return pair[1];
        }
    }
    return false;
}

function getQueryVariable(variable) {
    if (process.env.TARO_ENV === "h5") {
        var query = window.location.search.substring(1) || window.location.href.split('?')[1] || window.location.href;
        // console.log(query)
        var vars = query.split("&");
        for (var i = 0; i < vars.length; i++) {
            var pair = vars[i].split("=");
            if (pair[0] === variable) {
                return decodeURI(pair[1]);
            }
        }
        return (false);
    } else if (process.env.TARO_ENV === "weapp") {
        let RouterParmas = Taro.getCurrentInstance().router?.params
        if (!RouterParmas) return undefined
        return RouterParmas[variable] || undefined
    }
}

function getDateGap(date1, date2, type) {
    //兼容IE，IE不支持转化“-”符号拼接的日期格式
    date1 = date1.replace(/-/g, "/");
    date2 = date2.replace(/-/g, "/");
    var time1 = date1 ? new Date(date1) : new Date();
    var time2 = date2 ? new Date(date2) : new Date();
    var gap = time1 - time2;
    if (gap < 0) {
        return "";
    }
    var seconds = (gap / 1000).toFixed(2);
    var minutes = Math.floor(gap / 1000 / 60);
    var hours = String(gap / 1000 / 60 / 60).indexOf(".") !== -1 ? (gap / 1000 / 60 / 60).toFixed(2) : gap / 1000 / 60 / 60;
    if (type === "min") {
        return minutes;
    }
    return hours;
}

var Utils = {
    // 获取据当前时间的分钟差
    getDistanceTime: function (date) {
        let date1 = dayjs().valueOf()
        let date2 = dayjs(date).valueOf()

        let diffTime = date1 - date2
        let minute = Math.ceil(diffTime / 1000 / 60)
        return minute
    },
    //选择文件
    chooseFile: function (option) {
        const { count = 1, success, fail, complete, id } = option

        const res: any = {
            errMsg: 'chooseFile:ok',
            tempFilePaths: [],
            tempFiles: []
        }
        if (count && typeof count !== 'number') {
            res.errMsg = 'error,typeof count is error',
                console.error(res.errMsg)
            typeof fail === 'function' && fail(res)
            typeof complete === 'function' && complete(res)
            return Promise.reject(res)
        }

        if (Taro.getEnv() === Taro.ENV_TYPE.WEB) {
            const fileId = "MyUtilsChooseFile"
            let taroChooseImageId: any = document.getElementById(fileId)
            if (!taroChooseImageId) {
                let htmlInputElement: any = document.createElement("input");
                htmlInputElement.type = "file"
                htmlInputElement.setAttribute('id', fileId)
                htmlInputElement.setAttribute('style', 'position: fixed; top: -4000px; left: -3000px; z-index: -300;')
                if (count > 1) {
                    htmlInputElement.setAttribute('multiple', 'multiple')
                }
                document.body.appendChild(htmlInputElement)
                taroChooseImageId = document.getElementById(fileId)
            } else {
                if (count > 1) {
                    taroChooseImageId.setAttribute('multiple', 'multiple')
                } else {
                    taroChooseImageId.removeAttribute("multiple")
                }
            }

            // htmlInputElement.accept = "application/*"
            // htmlInputElement.accept = "application/pdf,application/vnd.ms-excel,application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
            // htmlInputElement.accept = "image/jpeg,image/gif,image/png"

            taroChooseImageId.onchange = (e) => {
                // console.log("onchange",e)
                let arr = [...e.target.files]
                arr = arr.splice(0, count)
                arr && arr.forEach(item => {
                    let blob = new Blob([item], {
                        type: e.target.files[0].type
                    });
                    let url = URL.createObjectURL(blob);
                    res.tempFilePaths.push(url)
                    // res.tempFiles.push({path: url, size: item.size, type: item.type, originalFileObj: item})
                    res.tempFiles.push({
                        path: url,
                        size: item.size,
                        type: item.type,
                        name: item.name,
                        id,
                        lastModified: item.lastModified,
                        lastModifiedDate: item.lastModifiedDate,
                        webkitRelativePath: item.webkitRelativePath
                    })
                })
                typeof success === "function" && success(res)
                typeof complete === "function" && complete(res)

                e.target.value = ''
                // document.body.removeChild(taroChooseImageId)
            }
            //触发选择
            taroChooseImageId.click()

        } else {
            Taro.chooseMessageFile({
                count: count,
                type: 'file',
                success: function (res) {
                    // console.log("选择文件",res)
                    success ? success(res) : ""
                }
            })
        }
    },
    chooseFile1: function (option) {
        const { count = 1, success, fail, complete } = option
        const res: any = {
            errMsg: 'chooseFile:ok',
            tempFilePaths: [],
            tempFiles: []
        }
        if (count && typeof count !== 'number') {
            res.errMsg = 'error,typeof count is error',
                console.error(res.errMsg)
            typeof fail === 'function' && fail(res)
            typeof complete === 'function' && complete(res)
            return Promise.reject(res)
        }

        if (Taro.getEnv() === Taro.ENV_TYPE.WEB) {
            const fileId = "MyUtilsChooseFile"
            let taroChooseImageId: any = document.getElementById(fileId)
            if (!taroChooseImageId) {
                let htmlInputElement: any = document.createElement("input");
                htmlInputElement.type = "file"
                htmlInputElement.setAttribute('id', fileId)
                htmlInputElement.setAttribute('style', 'position: fixed; top: -4000px; left: -3000px; z-index: -300;')
                if (count > 1) {
                    htmlInputElement.setAttribute('multiple', 'multiple')
                }
                document.body.appendChild(htmlInputElement)
                taroChooseImageId = document.getElementById(fileId)
            } else {
                if (count > 1) {
                    taroChooseImageId.setAttribute('multiple', 'multiple')
                } else {
                    taroChooseImageId.removeAttribute("multiple")
                }
            }

            // htmlInputElement.accept = "application/*"
            // htmlInputElement.accept = "application/pdf,application/vnd.ms-excel,application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
            // htmlInputElement.accept = "image/jpeg,image/gif,image/png"

            taroChooseImageId.onchange = (e) => {
                console.log("onchange", e)
                let arr = [...e.target.files]
                arr = arr.splice(0, count)
                arr && arr.forEach(item => {
                    let blob = new Blob([item], {
                        type: e.target.files[0].type
                    });
                    let url = URL.createObjectURL(blob);
                    res.tempFilePaths.push(url)
                    // res.tempFiles.push({path: url, size: item.size, type: item.type, originalFileObj: item})
                    // console.log("选择item",item)
                    res.tempFiles.push({
                        originalFileObj: item,
                        path: url,
                        size: item.size,
                        type: item.type,
                        name: item.name,
                        lastModified: item.lastModified,
                        lastModifiedDate: item.lastModifiedDate,
                        webkitRelativePath: item.webkitRelativePath
                    })
                })
                typeof success === "function" && success(res)
                typeof complete === "function" && complete(res)

                e.target.value = ''
                // document.body.removeChild(taroChooseImageId)
            }
            //触发选择
            taroChooseImageId.click()

        } else {
            Taro.chooseMessageFile({
                count: count,
                type: 'file',
                success: function (res) {
                    // console.log("选择文件",res)
                    success ? success(res) : ""
                }
            })
        }
    },
    //获取时间 _getTime(-7)前七天 2020-03-07
    getTime: function (day, type) {
        var today = new Date();
        if (day) {
            var targetday_milliseconds = today.getTime() + 1000 * 60 * 60 * 24 * day;
            today.setTime(targetday_milliseconds);
            var time = type ? " " + handleTime(today.getHours()) + ":" + handleTime(today.getMinutes()) : " 00:00:00";
        } else {
            if (type) {
                today.setTime(today.getTime() + 1000 * 60 * 5);
                var time = " " + handleTime(today.getHours()) + ":" + handleTime(today.getMinutes()) + ":00";
            } else {
                var time = " " + handleTime(today.getHours()) + ":" + handleTime(today.getMinutes()) + ":" + handleTime(today.getSeconds());
            }
        }
        return today.getFullYear() + "-" + handleTime(today.getMonth() + 1) + "-" + handleTime(today.getDate()) + time;
    },
    getDate: function (day, curTime) {
        var today = new Date();
        if (curTime) today.setTime(curTime);
        if (day) {
            var targetday_milliseconds = today.getTime() + 1000 * 60 * 60 * 24 * day;
            today.setTime(targetday_milliseconds);
        }
        return today.getFullYear() + "-" + handleTime(today.getMonth() + 1) + "-" + handleTime(today.getDate());
    },
    setDate: function (day) {
        var today = new Date();
        if (!day) return today;
        var dateList = day.split("-");
        today.setFullYear(parseInt(dateList[0]));
        today.setMonth(parseInt(dateList[1]) - 1);
        today.setDate(parseInt(dateList[2]));
        return today.getTime();
    },
    getDate1: function (day, curTime) {
        var dayList = ["周日", "周一", "周二", "周三", "周四", "周五", "周六"]
        var today = new Date();
        if (curTime) today.setTime(curTime);
        if (day) {
            var targetday_milliseconds = today.getTime() + 1000 * 60 * 60 * 24 * day;
            today.setTime(targetday_milliseconds);
        }
        var time = today.getFullYear() + "-" + handleTime(today.getMonth() + 1) + "-" + handleTime(today.getDate()),
            date = dayList[today.getDay()];
        return { time: time, date: date };
    },
    transformToPx: function (size) {
        var transSize = 0;
        Taro.getSystemInfo({
            success: res => {
                var width = res.windowWidth;
                if (process.env.TARO_ENV === 'weapp') {
                    transSize = size * (width / 750);
                } else { //if (process.env.TARO_ENV === 'h5') 
                    if (width >= 640) {
                        var baseSize = 40
                    } else if (width <= 320) {
                        var baseSize = 20
                    } else {
                        var baseSize = width / 320 * 20
                    }
                    transSize = Math.ceil(parseFloat(Taro.pxTransform(size)) * baseSize * 10000) / 10000;
                }
            }
        })
        return transSize;
    },
    //计算两个日期之间相隔多少小时
    getDateGap: function (date1, date2) {
        //兼容IE，IE不支持转化“-”符号拼接的日期格式
        date1 = date1.replace(/-/g, "/");
        date2 = date2.replace(/-/g, "/");
        var time1 = new Date(date1);
        var time2 = new Date(date2);
        var gap = Math.abs(time1 - time2);
        var seconds = (gap / 1000).toFixed(2);
        var minutes = (gap / 1000 / 60).toFixed(2);
        var hours = String(gap / 1000 / 60 / 60).indexOf(".") !== -1 ? (gap / 1000 / 60 / 60).toFixed(2) : gap / 1000 / 60 / 60;
        return hours;
    },
    // 获取倒计时距离的时间,返回一个对象其中包括天数、小时数和年
    getCutdown: function (endDate) {
        let obj = {}
        let startDate = Date.now()
        endDate = new Date(endDate.replace(/-/g, '/'))
        var diff = endDate.getTime() - startDate//时间差的毫秒数  

        if (diff < 0) {
            return false
        }

        //计算出相差天数  
        var days = Math.floor(diff / (24 * 3600 * 1000));

        //计算出小时数  
        var leave1 = diff % (24 * 3600 * 1000);    //计算天数后剩余的毫秒数  
        var hours = Math.floor(leave1 / (3600 * 1000));
        //计算相差分钟数  
        var leave2 = leave1 % (3600 * 1000);        //计算小时数后剩余的毫秒数  
        var minutes = Math.floor(leave2 / (60 * 1000));

        //计算相差秒数  
        var leave3 = leave2 % (60 * 1000);      //计算分钟数后剩余的毫秒数  
        var seconds = Math.round(leave3 / 1000);

        var returnStr = seconds + "秒";
        obj.seconds = seconds
        if (minutes > 0) {
            returnStr = minutes + "分" + returnStr;
            obj.minutes = minutes
        }
        if (hours > 0) {
            returnStr = hours + "小时" + returnStr;
            obj.hours = hours
        }
        if (days > 0) {
            returnStr = days + "天" + returnStr;
            obj.day = days
        }
        console.log(obj)
        return obj;
    },
    recentDateStr: function (date) {
        let nowTime = new Date();
        let difDay = nowTime.getDate() - new Date(date).getDate();
        let dif = nowTime.getHours() - new Date(date).getHours();
        let updateDate;
        if (!difDay) {
            if (dif > 0 && dif < 24) {
                if (dif === 1 && nowTime.getMinutes() - new Date(date).getMinutes() < 0) {
                    let difMinute = nowTime.getMinutes() - new Date(date).getMinutes() + 60;
                    updateDate = difMinute + '分钟前';
                } else {
                    updateDate = dif + '个小时前';
                }
            } else if (dif === 0) {
                let difMinute = nowTime.getMinutes() - new Date(date).getMinutes();
                updateDate = (difMinute && difMinute !== -1 ? difMinute : 1) + '分钟前';
            } else {
                updateDate = date.substring(0, 10);
            }
        } else {
            updateDate = date.substring(0, 10);
        }

        return updateDate;
    },
    //获取yyyy-mm-dd HH:MM:ss格式时间
    constructionDate: function (date, type) {
        date = date ? new Date(date.replace(/-/g, '/')) : new Date();
        var year = date.getFullYear();
        var month = date.getMonth() + 1;
        var day = date.getDate();
        var hour = date.getHours();
        var minute = date.getMinutes();
        var second = date.getSeconds();
        if (month < 10) {
            month = "0" + month;
        }
        if (day < 10) {
            day = "0" + day;
        }
        if (hour < 10) {
            hour = "0" + hour;
        }
        if (minute < 10) {
            minute = "0" + minute;
        }
        if (second < 10) {
            second = "0" + second;
        }
        if (type == 2) {
            return year + "-" + month + "-" + day + " " + hour + ":" + minute;
        }
        if (type == 3) {
            return year + "-" + month + "-" + day;
        }
        return year + "-" + month + "-" + day + " " + hour + ":" + minute + ":" + second;
    },
    //获取yyyy-mm-dd HH:MM:ss格式时间
    constructionDate2: function (date, type) {
        date = date ? new Date(date.replace(/-/, '/')) : new Date();
        console.log(date);

        var year = date.getFullYear();
        var month = date.getMonth() + 1;
        var day = date.getDate();
        var hour = date.getHours();
        var minute = date.getMinutes();
        if (month < 10) {
            month = "0" + month;
        }
        if (day < 10) {
            day = "0" + day;
        }
        if (hour < 10) {
            hour = "0" + hour;
        }
        if (minute < 10) {
            minute = "0" + minute;
        }
        if (type == 2) {
            return year + "-" + month + "-" + day + " " + hour + ":" + minute;
        }
        if (type == 3) {
            return year + "-" + month + "-" + day;
        }
        return year + "-" + month + "-" + day + " " + hour + ":" + minute;
    },
    /**  
    * @method getQueryVariable
    * @param { variable } 需要从url获取的键值
   **/
    //获取url参数
    getQueryVariable: function (variable) {
        var query = window.location.search.substring(1) || window.location.href.split('?')[1] || window.location.href;
        // console.log(query)
        var vars = query.split("&");
        for (var i = 0; i < vars.length; i++) {
            var pair = vars[i].split("=");
            if (pair[0] === variable) {
                return decodeURI(pair[1]);
            }
        }
        return (false);
    },
    // 获取当前文件的类型
    getTypeOfFile: function (variable) {
        var fileType = variable.split('.')[1]
        switch (variable.split('.')[1]) {
            case 'doc':
                fileType = 'word'
                break;
            case 'xls':
                fileType = 'xls'
                break;
            case 'ppt':
                fileType = 'ppt'
                break;
            case 'pptx':
                fileType = 'ppt'
                break;
            case 'pdf':
                fileType = 'pdf'
                break;
            case 'docx':
                fileType = 'word'
                break;
            case 'xlsx':
                fileType = 'xls'
                break;
            case 'pptx':
                fileType = 'ppt'
                break;
            case 'png':
                fileType = 'img'
                break;
            case 'jpg':
                fileType = 'img'
                break;
            case 'jepg':
                fileType = 'img'
                break;
            case 'txt':
                fileType = 'txt'
                break;
            case 'zip':
                fileType = 'zip'
                break;
            case '7z':
                fileType = 'zip'
                break;
            default:
                fileType = 'default'
                break;
        }
        return fileType
    },
    // 获取当前环境token
    getNowToken: function () {
        if (process.env.TARO_ENV === 'weapp') {
            return Taro.getApp().$app.globalData.Token
        } else {
            return storage.get('token') || getQueryVariable('lg_tk')
        }

    },
    getTimeDiff: function (date1, date2) {
        let mins = getDateGap(date1, date2, "min");
        if (!mins) {
            return "";
        }
        let day = 0, hour = 0, min = 0;
        day = Math.floor(mins / 60 / 24);
        hour = Math.floor((mins / 60) % 24);
        min = mins % 60;

        if (day >= 2) {
            return 0
        }

        return `${day ? day + '天' : ''}${hour ? hour + '小时' : ''}${min ? min + '分' : 0}`;
    },
    // 过滤所有html标签
    RemoveHTML: function (str) {
        return str.replace(/<\/?.+?\/?>/g, '').replace(/&nbsp;/, '');

    },
    // 获取中文日期：xxxx年xx月xx日 xx:XX
    getDateForChinese: function (str) {

        if (!str) {
            return ''
        }
        dayjs.extend(toObject)

        let newstr = ''
        let nowDate = dayjs()
        let nowDateObj = dayjs(nowDate).toObject()
        let strObj = dayjs(str).toObject()

        if (strObj['years'] == nowDateObj['years']) {
            if (strObj['mouths'] == nowDateObj['months']) {
                console.log('当前月')
                // 当月
                if (strObj['date'] = nowDateObj['date']) {
                    // 当天

                    newstr = `${strObj['hours'] >= 10 ? strObj['hours'] : '0' + strObj['hours']}:${strObj['minutes'] >= 10 ? strObj['minutes'] : strObj['minutes'] + '0'}`
                } else {
                    // 不是当天
                    newstr = `${strObj['months'] + 1}月${strObj['date']}日 ${strObj['hours'] >= 10 ? strObj['hours'] : '0' + strObj['hours']}:${strObj['minutes'] >= 10 ? strObj['minutes'] : strObj['minutes'] + '0'}`
                }
            } else {
                // 今年但不是当月
                newstr = `${strObj['months'] + 1}月${strObj['date']}日 ${strObj['hours'] >= 10 ? strObj['hours'] : '0' + strObj['hours']}:${strObj['minutes'] >= 10 ? strObj['minutes'] : strObj['minutes'] + '0'}`
            }
        } else {
            // 往年
            newstr = `${strObj['years']}年${strObj['months'] + 1}月${strObj['date']}日 ${strObj['hours'] >= 10 ? strObj['hours'] : '0' + strObj['hours']}:${strObj['minutes'] >= 10 ? strObj['minutes'] : strObj['minutes'] + '0'}`
        }
        return newstr
    },
    getCurrentDate:function(){
        dayjs.extend(toObject)

        let nowDate = dayjs()
        let nowDateObj = dayjs(nowDate).toObject()
        let year=nowDateObj['years']
        let month=nowDateObj['months']<10?'0'+nowDateObj['months']:nowDateObj['months']
        return year+''+month
    },
    getOutAvatar: function (avatarAddr:string,url:string) {
        if(!avatarAddr || url.indexOf('/http_basic/')<0 || this.getSystemInfo()==='h5'){
            return url
        }
        return avatarAddr + '/http_basic/'+url.split('/http_basic/')[1]
    },
    //获取聊天界面时间
    getChatTime: function (str) {

        if (!str) {
            return ''
        }

        let diff1 = dayjs(str)
        let diff2 = dayjs()
        let newstr = ''

        if (diff1.diff(diff2, 'year') == 0) {
            if (diff1.diff(diff2, 'month') == 0) {
                // 当月
                if (diff1.diff(diff2, 'day', true) > -0.5) {
                    // 当天
                    newstr = dayjs(str).format('HH:mm')
                } else {
                    // 不是当天
                    newstr = dayjs(str).format('MM-DD HH:mm')
                }
            } else {
                // 今年但不是当月
                newstr = dayjs(str).format('MM-DD HH:mm')
            }
        } else {
            // 往年
            newstr = dayjs(str).format('YYYY-MM-DD HH:mm')
        }
        return newstr
    },
    isClosetime: function (time1, time2) {
        if (!time1 || !time2) {
            return
        }
        let diff1 = dayjs(time1)
        let diff2 = dayjs(time2)
        let diffMinute = diff1.diff(diff2, 'minute')
        if (diffMinute <= 5) {
            return false
        } else {
            return true
        }
    },
    // 判断当前环境是否为wapp
    getNowEnvironment: function () {
        return process.env.TARO_ENV === 'weapp'
    },
    // 根据字节数计算文件大小
    getFileSize: function (fileByte) {
        // fileByte为字节大小
        var fileSizeByte = fileByte;

        var fileSizeMsg = "";
        // 1字节(Byte） = 8位(bit)   
        if (fileSizeByte < 1048576) {
            // 1KB=1024 字节
            fileSizeMsg = (fileSizeByte / 1024).toFixed(2) + "KB";
        } else if (fileSizeByte == 1048576) {
            fileSizeMsg = "1MB";
        } else if (fileSizeByte > 1048576 && fileSizeByte < 1073741824) {
            // 1MB=1024KB  （1024的2次方字节） 
            fileSizeMsg = (fileSizeByte / (1024 * 1024)).toFixed(2) + "MB";
        } else if (fileSizeByte > 1048576 && fileSizeByte == 1073741824) {
            fileSizeMsg = "1GB";
        } else if (fileSizeByte > 1073741824 && fileSizeByte < 1099511627776) {
            // 1GB=1024MB （1024的3次方字节） 
            fileSizeMsg = (fileSizeByte / (1024 * 1024 * 1024)).toFixed(2) + "GB";
        } else {
            // 1TB=1024GB （1024的4次方字节）
            fileSizeMsg = '25kb';
        }
        return fileSizeMsg;


    },
    // //根据文件名获取文件类型
    getFileTypeOf: function (name) {
        let index = name.lastIndexOf('.') + 1
        let len = name.length
        let type = name.slice(index, len)
        type = type.toLowerCase()
        let fileType = ""
        let obj = {
            "png": "img",
            "jpg": "img",
            "jpeg": "img",
            "doc": "doc",
            "docx": "doc",
            "xls": "xls",
            "xlsx": "xls",
            "zip": "zip",
            "7z": "zip",
            "rar": "zip",
            "jar": "zip",
            "kz": "zip",
            "mp3": "music",
            "cd": "music",
            "wave": "music",
            "aiff": "music",
            "mpeg": "music",
            "mp4": "video",
            "avi": "video",
            "rmvb": "video",
            "rm": "video",
            "wmv": "video",
            "asf": "video",
            "asx": "video",
            "txt": "txt",
            "html": "html",
            "ppt": "ppt",
            "pdf": "pdf",
        }
        if (!obj[type]) {
            fileType = "otr"
        } else {
            fileType = obj[type]
        }
        return fileType
    },
    //根据文件名获取文件类型
    getFileType: function (name) {
        let index = name.lastIndexOf('.') + 1
        let len = name.length
        let type = name.slice(index, len)
        type = type.toLowerCase()
        let fileType = ""
        let obj = {
            "png": "img",
            "jpg": "img",
            "jpeg": "img",
            "doc": "doc",
            "docx": "doc",
            "xls": "xls",
            "xlsx": "xls",
            "zip": "zip",
            "7z": "zip",
            "rar": "zip",
            "jar": "zip",
            "kz": "zip",
            "mp3": "music",
            "cd": "music",
            "wave": "music",
            "aiff": "music",
            "mpeg": "music",
            "mp4": "video",
            "avi": "video",
            "rmvb": "video",
            "rm": "video",
            "wmv": "video",
            "asf": "video",
            "asx": "video",
            "txt": "txt",
            "html": "html",
            "ppt": "ppt",
            "pdf": "pdf",
        }
        if (!obj[type]) {
            fileType = "otr"
        } else {
            fileType = obj[type]
        }
        return fileType
    },
    // 日期补零
    addZeroToDate: function (date) {
        let arr = date.split('-')
        arr && arr.forEach(item => {
            if (item < 10) {
                item = '0' + item
            }
        });
        console.log(arr);

        return arr.join('-')
    },
    getSystemInfo: function () {  //获取当前系统环境嵌入小程序/h5页面
        if (window.__wxjs_environment === 'miniprogram' || getQueryVariable('env') === 'weapp' || process.env.TARO_ENV === 'weapp') {
            return 'weapp'
        } else {
            return 'h5'
        }
    },

}
function handleTime(month) {
    if (month.toString().length == 1) {
        return "0" + month;
    }
    return month;
}

export default Utils 